package com.imyuanma.qingyun.common.config.security;

import com.imyuanma.qingyun.common.model.ECommonResultCode;
import com.imyuanma.qingyun.common.model.response.Result;
import com.imyuanma.qingyun.common.util.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证异常处理
 *
 * @author wangjy
 * @date 2022/07/18 23:11:21
 */
@Component
public class DefaultAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Logger logger = LoggerFactory.getLogger(DefaultAuthenticationEntryPoint.class);
    /**
     * Commences an authentication scheme.
     * <p>
     * <code>ExceptionTranslationFilter</code> will populate the <code>HttpSession</code>
     * attribute named
     * <code>AbstractAuthenticationProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY</code>
     * with the requested target URL before calling this method.
     * <p>
     * Implementations should modify the headers on the <code>ServletResponse</code> as
     * necessary to commence the authentication process.
     *
     * @param request       that resulted in an <code>AuthenticationException</code>
     * @param response      so that the user agent can begin authentication
     * @param authException that caused the invocation
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        logger.info("[认证异常处理] 认证异常处理,URI={}", request.getRequestURI());
        if (WebUtil.isAjaxRequest(request)) {
            WebUtil.write2Response(response, Result.error(ECommonResultCode.SESSION_TIMEOUT));
        } else {
            //请求的url
            response.sendRedirect("/page/login.html");
        }
    }
}
